/**
 * 
 */
package com.speedydial;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.speedydial.model.SMSContact;

/**
 * 
 * Activity to display the form in order to collect the data
 * for the people that you are going to notify when arriving late
 * @author mario
 *
 */
public class ContactFormActivity extends Activity {
	
	
	private SpeedyContactDBAdapter dbAdapter;
	
	private EditText name;
	private EditText phone;
	private EditText description;
	
	private Long objID;
	
	private Button confirmBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// create the whole bunch of initiation routines
		dbAdapter = new SpeedyContactDBAdapter(this);
		
		dbAdapter.open();
		
		setContentView(R.layout.contact_form);
		
		// now asignamos los elementos para luego referirnos y poder save them
		name = (EditText) findViewById(R.id.edit_name);
		phone = (EditText) findViewById(R.id.edit_name);
		description = (EditText) findViewById(R.id.edit_descr);
		
		confirmBtn = (Button) findViewById(R.id.ok_button);
		

		// in case is needed, we recover the id
		
		objID = (savedInstanceState == null ) ? null : 
				(Long)savedInstanceState.getSerializable(SpeedyContactDBAdapter.KEY_ROWID);
		
		// si no lo tenemos del estado en que supuestamente se guardo
		// lo obtenemos del intent y su respectivo bundle
		if( objID == null ){
			Bundle bundle = getIntent().getExtras();
			objID = (bundle == null ) ? null :
				(Long) bundle.getLong(SpeedyContactDBAdapter.KEY_ROWID);
		}
		
		// now add the handler for the button
		confirmBtn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
               
                setResult(RESULT_OK);
                finish();
            }
          
        });
	}
	
	
	
	@Override
	protected void onPause() {
		super.onPause();
		saveForm();
	}



	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		saveForm();
		outState.putSerializable(SpeedyContactDBAdapter.KEY_ROWID, objID);
		
	}



	private void saveForm(){
		
		String nameStr = name.getText().toString();
		String phoneStr = phone.getText().toString();
		String descrStr = description.getText().toString();
		
		SMSContact contact = new SMSContact(nameStr, phoneStr, descrStr,
				(objID == null) ? -1 : objID.intValue() );
		
		if ( objID == null){
			long idResult = dbAdapter.createContact(contact);
		} else {
			dbAdapter.updateSMSContact(contact);
		}
		
	}

}
